﻿using LiveCharts.Configurations;
using MySql.Data.MySqlClient;
using NewChillers.Helpers;
using NewChillers.Models;
using NewChillers.Models.Events;
using NewChillers.Utils;
using NewChillers.Views;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace NewChillers.ViewModels
{
    public class UserViewModel : ObservableObject
    {
        private UserModel _currentUser;
        private readonly ShellViewModel _shellViewModel;
        private List<UserModel> _userList; // 用户列表
        private bool _isUserListLoading;
        private string _txtSearch; // 搜索栏

        public List<UserModel> UserList
        {
            get => _userList;
            set => SetProperty(ref _userList, value);
        }
        public bool IsUserListLoading
        {
            get => _isUserListLoading;
            set => SetProperty(ref _isUserListLoading, value);
        }
        public string TxtSearch
        {
            get => _txtSearch;
            set => SetProperty(ref _txtSearch, value);
        }

        public ICommand EditCommand { get; } // 编辑
        public ICommand DeleteCommand { get; } // 删除

        public ICommand AddCommand { get; } // 添加用户
        public ICommand RefreshCommand { get; } // 手动刷新列表

        public ICommand SearchCommand { get; } // 查询按钮 模糊搜索

        public UserViewModel(UserModel userModel, ShellViewModel shellViewModel)
        {
            _currentUser = userModel;
            _shellViewModel = shellViewModel;

            TxtSearch = ""; // 清空搜索栏
            _ = InitUserListAsync();

            EditCommand = new RelayCommand<UserModel>(ExecuteEdit);
            DeleteCommand = new RelayCommand<UserModel>(ExecuteDelete);
            AddCommand = new RelayCommand(ExecuteAdd);
            RefreshCommand = new AsyncCommand(ExecuteRefresh);
            SearchCommand = new AsyncCommand(ExecuteSearch);

            // 订阅
            _shellViewModel.UserInfoUpdate += OnUserInfoUpdate;
        }

        #region 操作行
        private async Task ExecuteSearch(object obj)
        {
            await InitUserListAsync();
        }

        private async Task ExecuteRefresh(object obj)
        {
            TxtSearch = ""; // 清空搜索栏
            await InitUserListAsync();
        }

        private async void ExecuteAdd(object obj)
        {
            UserModel newUser = new UserModel(); // 添加新的
            try
            {
                // 创建对话框并传值  2:编辑  3:新增
                var userInfoView = new UserInfoView(newUser, 3, _currentUser);

                // 设置Owner建立窗口关系
                userInfoView.Owner = Application.Current.MainWindow;

                // 显示模态对话框并等待结果
                bool? result = userInfoView.ShowDialog();

                // 处理对话框返回结果
                if (result == true)
                {
                    Debug.WriteLine("用户进行了 [用户管理]添加用户 操作");

                    // 添加后 从数据库 重新获取用户信息
                    await InitUserListAsync();

                    LogHelper.Info(this.GetType(), "[用户管理] | 添加用户成功", _currentUser.UserAccount);
                }
                else if (result == false)
                {
                    // 用户取消了操作
                    Debug.WriteLine("用户取消了 [用户管理]添加用户 操作");
                    await InitUserListAsync();
                }
            }
            catch (Exception ex)
            {
                MsgBoxHelper.Error($"打开 [用户管理]添加用户 页面失败: {ex.Message}");
            }
        }

        private async void ExecuteDelete(UserModel selectedUser)
        {
            if (selectedUser == null)
                return;

            try
            {
                if (MsgBoxHelper.ConfirmYesNo($"确定要删除用户 {selectedUser.UserName} 吗？"))
                {
                    string sql = "DELETE FROM user_info WHERE user_account = @UserAccount";

                    MySqlParameter mySqlParameter = new MySqlParameter("@UserAccount", selectedUser.UserAccount);

                    int count = MysqlHelper.ExecuteNonQuery(sql, mySqlParameter);
                    //int count = await Task.Run(() => MysqlHelper.ExecuteNonQuery(sql, mySqlParameter));

                    if (count == 1)
                    {
                        await InitUserListAsync();

                        Debug.WriteLine("操作 [用户管理]删除 成功");
                        MsgBoxHelper.Info("操作 [用户管理]删除 成功，已刷新用户列表");
                        LogHelper.Info(this.GetType(), "[用户管理] | 删除用户成功" + $" 目标:{selectedUser.UserAccount}({selectedUser.UserName})", _currentUser.UserAccount);
                    }
                    else
                    {
                        MsgBoxHelper.Info("操作 [用户管理]删除 失败，未找到对应用户记录");
                    }
                }
                else
                    Debug.WriteLine("操作 [用户管理]删除 取消");
            }
            catch (Exception ex)
            {
                MsgBoxHelper.Error($"操作 [用户管理]删除 失败: {ex.Message}");
            }
        }

        private async void ExecuteEdit(UserModel selectedUser)
        {
            if (selectedUser == null)
                return;

            try
            {
                // 创建对话框并传值  2:编辑  3:新增
                var userInfoView = new UserInfoView(selectedUser, 2, _currentUser);

                // 设置Owner建立窗口关系
                userInfoView.Owner = Application.Current.MainWindow;

                // 显示模态对话框并等待结果
                bool? result = userInfoView.ShowDialog();

                // 处理对话框返回结果
                if (result == true)
                {
                    Debug.WriteLine("用户进行了 [用户管理]编辑 操作");

                    // 编辑后 从数据库 重新获取信息
                    await InitUserListAsync();

                    LogHelper.Info(this.GetType(), "[用户管理] | 修改用户成功", _currentUser.UserAccount);
                }
                else if (result == false)
                {
                    // 用户取消了操作
                    Debug.WriteLine("用户取消了 [用户管理]编辑 操作");
                    await InitUserListAsync();
                }
            }
            catch (Exception ex)
            {
                MsgBoxHelper.Error($"打开 [用户管理]编辑 页面失败: {ex.Message}");
            }
        }
        #endregion

        #region 显示
        private async Task InitUserListAsync()
        {
            // 防止重复加载
            if (IsUserListLoading)
                return;

            IsUserListLoading = true;

            try
            {
                var sqlBuilder = new StringBuilder("SELECT * FROM user_info");
                List<MySqlParameter> parameters = new List<MySqlParameter>();

                if (!string.IsNullOrEmpty(TxtSearch))
                {
                    sqlBuilder.Append(" WHERE user_name LIKE @UserName OR user_account LIKE @UserAccount");
                    parameters.Add(new MySqlParameter("@UserName", MySqlDbType.VarChar) { Value = "%" + TxtSearch + "%" });
                    parameters.Add(new MySqlParameter("@UserAccount", MySqlDbType.VarChar) { Value = "%" + TxtSearch + "%" });
                }

                Func<IDataRecord, UserModel> mapper = reader => new UserModel
                {
                    UserAccount = reader["user_account"].ToString(),
                    UserName = reader["user_name"].ToString(),
                    UserPassword = reader["user_password"].ToString(),
                    UserIdentity = Convert.ToInt32(reader["user_identity"])
                };

                // 直接使用异步方法，不需要 Task.Run
                var users = await MysqlHelper.ExecuteQueryAsync<UserModel>(sqlBuilder.ToString(), mapper, parameters.ToArray());

                UserList = users;
            }
            catch (Exception ex)
            {
                LogHelper.Error(this.GetType(), "[加载用户] | 用户列表加载失败", ex, _currentUser.UserAccount);
                UserList = new List<UserModel>();
            }
            finally
            {
                IsUserListLoading = false;
            }
        }
        #endregion

        #region 更新当前登录用户的信息 事件处理
        /// <summary>
        /// 接收到通知
        /// </summary>
        private void OnUserInfoUpdate(object sender, UserInfoUpdateEventArgs e)
        {
            // 空值检查，避免NullReferenceException
            if (e?.UpdatedUser != null)
            {
                _currentUser = e.UpdatedUser;
                Debug.WriteLine("User页面|用户信息已更新");
            }
            else
            {
                Debug.WriteLine("收到空的事件参数");
            }
        }

        /// <summary>
        /// 析构函数中的事件取消订阅
        /// </summary>
        ~UserViewModel()
        {
            _shellViewModel.UserInfoUpdate -= OnUserInfoUpdate;
        }
        #endregion
    }
}
